<template>
  <div class="comment-container">
    <h3>发表评论</h3>
    <hr />
    <textarea
      placeholder="不能多BB，最多120个字"
      maxlength="120"
      v-model="msg"
    ></textarea>

    <el-button type="primary" @click="postMsg">发表评论</el-button>

    <div class="list">
      <div class="item" v-for="(item, i) in commentList" :key="item.id">
        <div class="title">
          第{{ i + 1 }}楼 &nbsp 用户：{{ item.user_name }} &nbsp 发表时间:{{
            item.add_time | dateFormat("YYYY-MM-DD HH:mm:ss")
          }}
        </div>
        <div class="body">
          {{
            item.content === "undefined" ? "这个人很懒什么都没写" : item.content
          }}
        </div>
      </div>
    </div>

    <el-button type="danger" plain size="lager" @click="getMore"
      >加载更多</el-button
    >
  </div>
</template>

<script>
export default {
  data() {
    return {
      pageIndex: 1,
      commentList: [],
      msg: "",
    };
  },
  created() {
    this.getComment();
  },
  methods: {
    getComment() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then((result) => {
          if (result.body.status === 0) {
            this.commentList = this.commentList.concat(result.body.message);
          } else {
            this.$message({
              message: "失败",
              type: "error",
            });
          }
        });
    },

    getMore() {
      this.pageIndex++;
      this.getComment();
    },

    postMsg() {

      if(this.msg.trim().length === 0){

          this.$message({

              message: "评论不能为空",
              type: "error"

          })

      }

      this.$http
        .post("api/postcomment/" + this.id, {
          content: this.msg.trim(),
        })
        .then((result) => {

            if(result.body.status === 0){

                //提交的内容
                var newMsg = {

                    user_name : "匿名用户",
                    add_time : new Date(),
                    content : this.msg.trim()

                }

                this.commentList.unshift(newMsg)
                this.msg = ""

            }

        });
    },
  },
  props: ["id"],
};
</script>

<style lang="scss" scoped>
.comment-container {
  h3 {
    font-size: 18px;
    margin-top: 20px;
  }

  hr {
    margin: 10px 0;
  }

  margin-bottom: 40px;

  textarea {
    margin-bottom: 5px;
    font-size: 12px;
  }

  .el-button {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 40px;
  }

  .title {
    font-size: 12px;
    line-height: 30px;
    background-color: darkgray;
    margin: 10px 0;
  }

  .body {
    font-size: 14px;
  }
}
</style>